[leetcode 156]Binary Tree Upside Down

来源:互联网 发布:js登录表单验证 编辑:程序博客网 时间:2024/04/30 02:44

Question:

Given a binary tree where all the right nodes are either leaf nodes with a sibling (a left node that shares the same parent node) or empty, flip it upside down and turn it into a tree where the original right nodes turned into left leaf nodes. Return the new root.
For example:
Given a binary tree {1,2,3,4,5},
    1   / \  2   3 / \4   5
return the root of the binary tree [4,5,2,#,#,3,1].
   4  / \ 5   2    / \   3   1  

分析:
题目大意就是给定的二叉树,要么没有右节点,要么右节点为叶子节点。然后将二叉树从下到上从翻转。
两个思路:
1、自顶向下方法--迭代规则是:
某个位置节点node的右节点变为父节点;node的左节点变为父节点的右节点。
所以依次向左分支迭代即可。
2、自下向上方法--递归
就是一直往左走到叶子节点,返回该点作为新的根节点newRoot,定义newRoot.left, newRoot.right变换规则同上, 再返回newRoot.right作为上一层的newRoot。

代码如下:
<span style="font-size:14px;">1、自顶向下--迭代/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    public TreeNode upsideDownBinaryTree(TreeNode root) {        if (root == null) {            return null;        }                 TreeNode parent = null;        TreeNode parentRightChild = null;        TreeNode p = root;                 while (p != null) {            TreeNode next = p.left;            p.left = parentRightChild;            parentRightChild = p.right;                         p.right = parent;                         parent = p;            p = next;        }                 return parent;    }}2、自下向上方法--递归/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    public TreeNode upsideDownBinaryTree(TreeNode root) {        if (root == null) {            return null;        }                 return upsideDownBinaryTreeHelper(root, null);    }         private TreeNode upsideDownBinaryTreeHelper(TreeNode root, TreeNode parent) {        if (root == null) {            return parent;        }                 TreeNode newNode = upsideDownBinaryTreeHelper(root.left, root);                 root.left = parent == null ? null : parent.right;        root.right = parent;                 return newNode;    }}</span>


0 0