バイナリ画像(再帰的に、leetcode 226):安全プランを証明します

トピック:

所与のバイナリツリーの動作は、バイナリツリーは、ソース画像に変換されます。

バイナリツリーの定義をミラーリング:
ソースバイナリ
    	    8 
    	   / \ 
    	  610 
    	 / \ / \ 
    	57911 
ミラーバイナリ
    	    8 
    	   / \ 
    	  106 
    	 / \ / \ 
    	11975

回答:

解決策1:

再帰的には、次の通り:

/**
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
public class Solution {
    public void Mirror(TreeNode root) {
        if(root==null||(root.left==null&&root.right==null)){
            return;
        }
        TreeNode temp = root.left;
        root.left = root.right;
        root.right = temp;
        Mirror(root.left);
        Mirror(root.right);
        return ;
        
    }
}

対処方法2:

深さ優先探索に似て反復法、次のように、キューを使用します。

public class Solution {
    public void Mirror(TreeNode root) {
        if(root==null||(root.left==null&&root.right==null)){
            return;
        }
        LinkedList<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while(!queue.isEmpty()){
            TreeNode node = queue.remove();
            TreeNode temp = node.left;
            node.left = node.right;
            node.right = temp;
            if(node.left!=null) queue.add(node.left);
            if(node.right!=null) queue.add(node.right);
        }
        return ;
        
    }
}

 

公開された92元の記事 ウォンの賞賛2 ビュー8409

おすすめ

転載: blog.csdn.net/wyplj2015/article/details/104867128